package com.cs543.j.client.cloudService.storage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.cs543.j.client.cloudService.Client;
import com.cs543.j.client.cloudService.LocalClient;
import com.cs543.j.client.cloudService.filesystem.Directory;
import com.cs543.j.client.cloudService.filesystem.Entry;

public class LocalStorage extends Storage {

	public static final String SDCARD_ROOT_DIR = "/mnt/sdcard";

	public LocalStorage(Client client) {
		super(client);
		if (!(client.isLocalClient() && client.getName().equals(LocalClient.LOCAL_SDCARD_NAME))) {
			throw new java.lang.IllegalArgumentException("Not Local SD card client");
		}
	}

	@Override
	public void lookup(Directory directory, OnLookupResponceListener listener) {

		File target = null;
		if (directory.isRootDirectory()) {
			target = new File(SDCARD_ROOT_DIR);
		} else {
			target = new File(SDCARD_ROOT_DIR + directory.getPath());
		}
		File[] fileList = target.listFiles();
		if (!target.exists() || fileList == null || fileList.length == 0) {
			listener.onLookupResponce(null);
		}

		Entry[] entryList = new Entry[fileList.length];

		for (int i = 0; i < fileList.length; i++) {
			File each = fileList[i];
			if (each.isDirectory())
				entryList[i] = new Directory(each.getName(), directory);
			else
				entryList[i] = new com.cs543.j.client.cloudService.filesystem.File(each.getName(), directory);
		}
		
		listener.onLookupResponce(entryList);
	}
	
	

}
